import axios        from 'axios'
import Vue          from 'vue'
import {BigNumber}  from 'bignumber.js'
import { Toast,Dialog }    from 'vant'
Vue.use(Toast,Dialog)
axios.defaults.timeout =  1000*15;

let debug = false;
//根据URL判断接口地址
let ajaxUrl = () => {
    let _url = window.location.href;
    let result = sessionStorage.getItem('ajaxBaseUrl');
    if(!result){
        if(_url.indexOf('dev') > -1){
            //开发环境
            result = 'https://dev-mapi.bbj.ai'
        }else if(_url.indexOf('uat') > -1 || _url.indexOf('127.0') > -1 || _url.indexOf('local') > -1){
            //uat环境
            result = 'https://uat-mapi.bbj.ai'
        }else if(_url.indexOf('pre') > -1){
            //预发布环境
            result = 'https://pre-mapi.bbj.ai'
        }else{
            //生产环境
            result = 'https://mapi.bbj.ai'
        }
        sessionStorage.setItem('ajaxBaseUrl',result);
    }
    return result
}
let time      = 10000;           //重复获取实时价格时间配置

//判断是否嵌入bbj app中
let inBBJ = () => {
    // return true
    return window.navigator.userAgent.indexOf('3RAPP') > -1
}

//判断是否嵌入mykey中
function isMYKEY(){
    return window.navigator.userAgent.indexOf("MYKEY") > -1;
}

//判断是否iphone x
let isIphoneX = () => {
    // return true
    if (typeof window !== 'undefined' && window && client()) {
        return /iphone/gi.test(window.navigator.userAgent) && window.screen.height >= 812;
    }
    return false
}

//设置cookie
let setCookie = (name, value) => {
    var Days = 30;
    var exp = new Date()
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
    document.cookie =
        name +
        '=' +
        escape(value) +
        ';expires=' +
        exp.toGMTString() +
        ';path=/;domain=.bbj.ai;'
}

//读取cookie
let getCookie = name => {
    var arr,reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
    if ((arr = document.cookie.match(reg))){
        return unescape(arr[2]) 
    }else{
        return null
    }
}

//删除cookie
let delCookie = name => {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null) document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString()
}


//返回token
let getToken = () => {
    let _token = getStorage('token');
    return window.token || getCookie('localToken') || _token || ''
}

let eosNetwork = {
    blockchain: 'eos', 
    chainId:'aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906', 
    host: 'nodes.get-scatter.com',
    port: 443,
    protocol: 'https' 
}

function getAccounts(web3){
    return new Promise(resolve => {
        web3.eth.getAccounts(function(error, accounts){
            resolve(accounts[0])
        });
    })
}

//定时获取ETH地址
function setIntervalGetAccounts(web3){
    let ETHAccount = sessionStorage.getItem('ETHAccount');
    if(!ETHAccount){
        web3.eth.getAccounts(function(error, accounts){
            if(accounts && accounts[0]){
                sessionStorage.setItem('ETHAccount',accounts[0]);
            }
        })
        setTimeout(()=>{
            setIntervalGetAccounts(web3)
        },800)
    }
}

//获取EOS账号
function getEOSName(){
    return new Promise(resolve => {
        let _EOSName = sessionStorage.getItem('EOSAccount');
        if(_EOSName){
            resolve(_EOSName)
        }else{
            let network = ScatterJS.Network.fromJson(eosNetwork);
            ScatterJS.connect('LernaVanillaTest', { network }).then(connected => {
                if (!connected) return false;
                let login = async () => {
                    await ScatterJS.login();
                    let accountInfo = ScatterJS.account('eos');
                    resolve(accountInfo.name)
                    sessionStorage.setItem('EOSAccount',accountInfo.name);
                    // setStorage('EOSAccount',accountInfo.name)
                };
                login();
            });
        }
    })
}

/**
 * 封装mykey jsbridge方法获取用户信息
 * @return {object} 当前用户账户信息
 */
function getAccountInfo(){
    return new Promise(resolve => {
        //先检测是否存在临时缓存，若存在则用缓存中的信息
        let sessionAccountInfo = sessionStorage.getItem('_accountInfo');
        if(sessionAccountInfo){
            resolve(JSON.parse(sessionAccountInfo));
            return
        }
        if(window.MyKey && window.MyKey.Browser && window.MyKey.Browser.getAccountInfo){
            window.MyKey.Browser.getAccountInfo(false).then(res => {
                let _accountInfo = (!res || res.errorCode != 0)?{}:res.data;
                //临时缓存mykey用户信息，确保一次会话只调用一次
                sessionStorage.setItem('_accountInfo',JSON.stringify(_accountInfo))
                resolve(_accountInfo)
            })
        }
    })
}

/**
 * uuid换取随机字符串
 * @param  {string} uuid mykey用户唯一标识
 * @return {string}      随机字符串
 */
let getRandom = uuid => {
    return new Promise(resolve => {
        fetch(ajaxUrl()+`/site/mykey-salt`,{
            uuid:uuid
        }).then(res => {
            resolve(res && res.retData && res.retData.salt?res.retData.salt:'')
        })
    })
}

/**
 * EOS链签名
 * @param  {string} EOSPublicKey 用户公钥地址(即操作码)
 * @param  {string} signedString 随机字符串
 * @return {string} signed       签名内容
 */
const EOSSign = (EOSPublicKey,signedString) => {
    return new Promise((resolve,reject) => {
        if(window.scatter){
            //若存在scatter缓存，则直接签名
            window.scatter.getArbitrarySignature(EOSPublicKey, signedString, 'Testing', false).then(signed => {
                resolve(signed?signed:'')
            })
        }else{
            //获取scatter值
            ScatterJS.connect('LernaVanillaTest', {
                network
            }).then(connected => {
                if (!connected){
                    Toast('ScatterJS链接失败，请退出重试！')
                    return false; 
                }
                window.scatter = ScatterJS.scatter;
                window.scatter.getArbitrarySignature(EOSPublicKey, signedString, 'Testing', false).then(signed => {
                    resolve(signed?signed:'')
                })
            })
        }
    })
}

/**
 * ETH签名方法
 * @param  {string} ETHName    ETH账户地址
 * @param  {string} randString 随机字符串
 * @return {string}            签名结果
 */
const ETHSign = (ETHName,randString) => {
    return new Promise(resolve => {
        if(typeof web3 != 'undefined'){
            web3.eth.sign(ETHName,randString,function(error,signed){
                resolve(error?'':signed)
            })
        }else{
            resolve('')
        }
    })
}

/**
 * 登录提交接口
 * @param  {string} uuid     mykey用户唯一表示
 * @param  {string} _EOSName EOS账户地址(EOS用户名)
 * @param  {string} _ETHName ETH账户地址
 * @param  {number} type     签名类型  1:EOS签名  2:ETH签名
 * @param  {string} signed   签名结果
 * @return {object}          返回的用户信息，格式如其中的userInfo变量
 */
const mykeyNew = (uuid,_EOSName,_ETHName,type,signed) => {
    return new Promise(resolve => {
        Toast.loading({
            message: '正在验签',
            duration:0,
            forbidClick: true
        })
        fetch(ajaxUrl()+`/site/mykey-new`,{
            app_id:2,   // 2:myotc 3:mykey
            uuid:uuid,
            EOS:_EOSName,
            ETH:_ETHName,
            type:type,
            signed:signed,
        }).then(res => {
            if(res && res.retCode == 0){
                let token = res.retData.token;
                localStorage.setItem('token',token)
                sessionStorage.setItem('token',token)
                resolve(token);
            }else{
                resolve(res)
            }
        })
    })
}

/**
 * [登录组件]
 * @author BBJ
 * @param {string} uuid mykey用户唯一标识
 * @param {string} EOSName EOS地址
 * @param {string} ETHName ETH地址
 * @param {string} key EOS签名操作码
 * @param {string} signed 签名结果
 * @return {Object} userInfo
 */
export const login = async () => {
    Toast.loading({
        message: '发起验签',
        duration:0,
        forbidClick: true
    })
    let accountInfo = await getAccountInfo();                                     //与mykey交互获取用户信息
    let uuid     = accountInfo.id;                                                //uuid
    let _EOSObj  = accountInfo.chainInfoList.filter(item => item.chain === 'EOS')[0];  //EOS账号
    let _ETHObj  = accountInfo.chainInfoList.filter(item => item.chain === 'ETH')[0];  //ETH账号
    let key      = accountInfo.operationKeys[2];                                  //operationKey
    if(!uuid) return '获取uuid失败，请先升级app';
    if(!_EOSObj && !_ETHObj) {
        return {
            retMsg:'请先开通EOS或ETH账号',
            hasOpen:true
        }
    }
    if(!key) return '获取EOS key失败，请联系客服';

    if(_EOSObj){
        sessionStorage.setItem('EOSAccount',_EOSObj.account);
        localStorage.setItem('EOSAccount',_EOSObj.account);
    }
    if(_ETHObj){
        sessionStorage.setItem('ETHAccount',_ETHObj.account);
        localStorage.setItem('ETHAccount',_ETHObj.account);
    }

    // uuid换取随机字符串
    let randString = await getRandom(uuid);
    if(!randString) return '获取随机字符串失败';

    if(_EOSObj && _EOSObj.account){
        //若无ETH，则使用EOS签名
        let signed = await EOSSign(key,randString);
        if(signed && signed.indexOf('取消') == -1){
            let token = await mykeyNew(uuid,_EOSObj.account,_ETHObj?_ETHObj.account:'',1,signed);
            return token
        }else{
            return 'EOS签名失败'
        }
    }else if(_ETHObj && _ETHObj.account){
        //优先使用ETH签名
        let signed = await ETHSign(_ETHObj.account,randString);
        if(signed){
            let token = await mykeyNew(uuid,_EOSObj?_EOSObj.account:'',_ETHObj.account,2,signed);
            return token
        }else{
            return 'ETH签名失败'
        }
    }else{
        return {
            retMsg:'请先开通EOS或ETH账号',
            hasOpen:true
        }
    }

    //全局临时缓存用户链路开通状态(忽略未开通情况，未开通的话走不到这一步，与登录无关)
    let userStatus = 0;
    if(_EOSObj && !_ETHObj){
        //只开通EOS
        userStatus = 1;
    }else if(!_EOSObj && _ETHObj){
        //只开通了ETH
        userStatus = 2;
    }else if(_EOSObj && _ETHObj){
        //EOS跟ETH都开通
        userStatus = 3;
    }
    sessionStorage.setItem('userStatus',userStatus)
}

let waitSDKReady = _from => {
    return new Promise((resolve,reject) => {
        if(debug) {
            //浏览器调试开发模式
            resolve(getStorage('token'));
            return
        }
        if(isMYKEY()){
            if(_from && _from == 'index'){
                //首页首次进入无需登录
                getAccountInfo().then(accountInfo => {
                    let _EOSObj  = accountInfo.chainInfoList.filter(item => item.chain === 'EOS')[0];  //EOS账号
                    let _ETHObj  = accountInfo.chainInfoList.filter(item => item.chain === 'ETH')[0];  //ETH账号
                    if(_EOSObj){
                        sessionStorage.setItem('EOSAccount',_EOSObj.account);
                        localStorage.setItem('EOSAccount',_EOSObj.account);
                    }
                    if(_ETHObj){
                        sessionStorage.setItem('ETHAccount',_ETHObj.account);
                        localStorage.setItem('ETHAccount',_ETHObj.account);
                    }
                    resolve(getStorage('token')?getStorage('token'):'');
                })
                return
            }
            if(sessionStorage.getItem('token')){
                //一次会话只验签登录一次
                resolve(sessionStorage.getItem('token'));
                return
            }
            /*
                在mykey中，上面部分为后来重构代码，else后的为适配老版本
            */
            let token = localStorage.getItem('token');
            if(token){
                //若有缓存，则直接使用缓存
                resolve(token)
                return
            }else if(window.MyKey && window.MyKey.Browser && window.MyKey.Browser.getAccountInfo){
                //适配新版本
                login().then(token => {
                    Toast.clear();
                    if(typeof token == 'object') Toast(token.retMsg)
                    resolve(token)
                }).catch(e => {
                    Toast.clear();
                })
            }else{
                //保留老版本适配(不久后可以去掉，或者一直保留也没问题)
                let ETHAccount = sessionStorage.getItem('ETHAccount');
                let EOSAccount = sessionStorage.getItem('EOSAccount');
                if(token && EOSAccount && ETHAccount){
                    if(_from && _from === 'index'){
                        //仅限首页校验
                        getEOSName().then(_EOSName => {
                            if(EOSAccount === _EOSName){
                                //先返回token，再异步检测token是否过期，每次会话仅判断一次token是否过期
                                resolve(token);
                                //判断token是否有效
                                let hasCheckedToken = sessionStorage.getItem('hasCheckedToken');
                                if(!hasCheckedToken){
                                    fetch(ajaxUrl()+`/user/verified-info`,{
                                        token:getToken()
                                    }).then(res => {
                                        if(res.retCode === 0){
                                            sessionStorage.setItem('hasCheckedToken',1)
                                            return
                                        }else{
                                            sessionStorage.removeItem('hasCheckedToken');
                                            sessionStorage.removeItem('token');
                                            window.location.reload();
                                        }
                                    }).catch(error => {
                                        sessionStorage.removeItem('hasCheckedToken');
                                        sessionStorage.removeItem('token');
                                        window.location.reload();
                                        console.log(error)
                                    })
                                }
                            }
                        })
                    }else{
                        //非首页若判断有token缓存，则直接使用
                        resolve(token);
                        return
                    }
                    return
                }

                if (typeof web3 !== 'undefined') {
                    web3 = new Web3(web3.currentProvider);
                    getAccounts(web3).then(accounts => {
                        alert(accounts)
                        //先获取用户ETH地址，之后再获取当前用户登录地址(EOS用户名，也是用户EOS地址)
                        if(accounts) sessionStorage.setItem('ETHAccount',accounts);
                        //可能存在的重复获取
                        setIntervalGetAccounts(web3)
                        Toast.loading({
                            message: '登录中...',
                            duration:0,
                            forbidClick: true
                        });
                        getEOSName().then(_EOSName => {
                            window.MyKey.Browser.getAccountInfo().then(res => {
                                let _accountInfo = (!res || res.errorCode != 0)?{}:res.data;
                                if(!_accountInfo.id){
                                    Toast("请先升级mykey");
                                }else{
                                    fetch(ajaxUrl()+'/site/mykey',{
                                        account:_EOSName,
                                        uuid:_accountInfo.id
                                    }).then(res => {
                                        if(res.retCode == 0){
                                            Toast.clear();
                                            resolve(res.retData.token)
                                            sessionStorage.setItem('token',res.retData.token);
                                        }
                                    })
                                }
                            })
                        })
                    })
                } else {
                    Toast("web3准备失败，请退出重试");
                }
            }
        }
    })
}

let fetch = (_url,datas) => {
    return new Promise((resolve,reject) => {
        axios.post(_url,datas,{timeout:1000*15}).then(res => {
            // console.log(res)
            if(res.status === 200){
                resolve(res.data)
                if(res.data.retCode == 100002){
                    //token过期情况处理
                    if(inBBJ()){
                        window.token = '';
                        localStorage.removeItem('token');
                        delCookie('localToken');
                        window.location.reload();
                    }else{
                        // alert('登录超时，请退出重新进入')
                    }
                }
            }else{
                reject(res)
                Toast('服务器错误')
            }
        }).catch(res => {
            reject('');
            console.log(res)
            // console.log(JSON.stringify(res))
            // Toast('网络繁忙，请稍后再试')
        })
    })
}


let fetch2 = (_url,datas) => {
    return new Promise((resolve,reject) => {
        axios.get(_url,{params:datas}).then(res => {
            if(res.status === 200){
                resolve(res.data)
                if(res.data.retCode === 100002){
                    //token过期情况处理
                    // if(inBBJ() && window.location.hash.indexOf('my') == -1){
                    //     window.token = '';
                    //     localStorage.removeItem('token');
                    //     window.location.reload();
                    // }else{
                    //     // alert('登录超时，请退出重新进入')
                    // }
                }
            }else{
                reject(res)
                Toast('服务器错误')
            }
        }).catch(res => {
            reject('');
            // Toast('网络繁忙，请稍后再试')
            console.log(res)
        })
    })
}

let getQueryString = function(name) {
    if (!name) return null
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search == "" ? null : decodeURIComponent(window.location.search).substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null
}

//判断客户端为安卓还是IOS
let client = () => /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent) ? true : false

let digitLength = (num) => {
    if(!num) return 0
    const eSplit = num.toString().split(/[eE]/);
    const len = (eSplit[0].split('.')[1] || '').length - (+(eSplit[1] || 0));
    return len > 0 ? len : 0;
}

//精确加法
let accAdd = (num1, num2) => {
    const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)));
    return (accMul(num1, baseNum) + accMul(num2, baseNum)) / baseNum;
}

//精确减法
let subtr = (num1, num2) => {
    const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)));
    return (accMul(num1, baseNum) - accMul(num2, baseNum)) / baseNum;
}

//精确乘法
let accMul = (num1, num2) => {
    return Number(BigNumber(num1).multipliedBy(num2).toString())
    const num1Changed = num1?Number(num1.toString().replace('.', '')):0;
    const num2Changed = num2?Number(num2.toString().replace('.', '')):0;
    const baseNum = digitLength(num1) + digitLength(num2);
    return num1Changed * num2Changed / Math.pow(10, baseNum);
}

//精确相除
let accDiv = (num1, num2) => {
    const num1Changed = num1?Number(num1.toString().replace('.', '')):0;
    const num2Changed = num2?Number(num2.toString().replace('.', '')):0;
    return accMul((num1Changed / num2Changed), Math.pow(10, digitLength(num2) - digitLength(num1)));
}

//设置本地缓存
let setStorage = (_key='bbj',_val) => {
    if(!_val) return
    if(typeof localStorage === 'object' && typeof localStorage.setItem === 'function'){
        localStorage.setItem(_key,typeof _val === 'object'?JSON.stringify(_val):_val)
    }else{
        Toast('手机不支持localStorage缓存')
    }
}
//设置本地缓存
let setStorage2 = (_key='bbj',_val) => {
    if(!_val) return
    if(typeof sessionStorage === 'object' && typeof sessionStorage.setItem === 'function'){
        sessionStorage.setItem(_key,typeof _val === 'object'?JSON.stringify(_val):_val)
    }else{
        Toast('手机不支持localStorage缓存')
    }
}
//读取本地缓存
let getStorage = _key => {
    if(typeof localStorage === 'object' && typeof localStorage.getItem === 'function'){
        return localStorage.getItem(_key)
    }else{
        Toast('手机不支持localStorage缓存');
    }
}

//读取本地缓存
let getStorage2 = _key => {
    if(typeof sessionStorage === 'object' && typeof sessionStorage.getItem === 'function'){
        return sessionStorage.getItem(_key)
    }else{
        Toast('手机不支持localStorage缓存');
    }
}

//根据币种名称获取价格
let getPriceByName = (name,type,number,from) => {
    return new Promise((resolve,reject) => {
        let _url = isMYKEY()?ajaxUrl()+`/site/mykey-otc-price`:ajaxUrl()+`/otc/price`;
        fetch(_url,{
            token:getToken(),
            currency_id:name,
            type:type,
            number:+number || 1
        }).then(res => {
            if(res.retCode === 0){
                if(from && from === 'index'){
                    resolve(res.retData)
                }else{
                    resolve(+res.retData.price)
                }
            }else{
                reject(res.retMsg || res.retData)
                Toast(res.retMsg || res.retData || '未知错误')
            }
        }).catch(error => {
            console.log(error)
        })
    })
}

let bridgeData = list => {
    //转换支付、付款格式
    return new Promise((resolve,reject) => {
        try{
            let _dot = process.env.NODE_ENV === 'development'?'../../':'./';
            list.sort((a,b) => b.recommend - a.recommend);
            list.map(item => {
                item.isSelected = item.recommend==1?true:false;
                if(item.type==1){
                    //支付宝
                    item.name = '支付宝';
                    item.icon = _dot+'static/images/alipay.png';
                }else if(item.type==2){
                    //银行卡
                    item.name = '银行卡';
                    item.icon = _dot+'static/images/bankCard.png';
                }else if(item.type==3){
                    //微信
                    item.name = '微信';
                    item.icon = _dot+'static/images/weixin.png';
                }
            })
            resolve(list)
        }catch(e){
            reject(e)
        }
    })
}


let transTime = (temp,tip) => {
    //确保时间戳为13位
    temp = temp.toString().length==10?temp*1000:temp;
    Date.prototype.format = function(format) {
        if (isNaN(this)) return '';
        var o = {
            'm+': this.getMonth() + 1,
            'd+': this.getDate(),
            'h+': this.getHours(),
            'n+': this.getMinutes(),
            's+': this.getSeconds(),
            'S': this.getMilliseconds(),
            'W': ["日", "一", "二", "三", "四", "五", "六"][this.getDay()],
            'q+': Math.floor((this.getMonth() + 3) / 3)
        };
        if (format.indexOf('am/pm') >= 0) {
            format = format.replace('am/pm', (o['h+'] >= 12) ? '下午' : '上午');
            if (o['h+'] >= 12) o['h+'] -= 12;
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }
    let postYear     = new Date(temp).format('yyyy');
    let postMonth    = new Date(temp).format('mm');
    let postDate     = new Date(temp).format('dd');
    let postHours    = new Date(temp).format('hh');
    let postMinutes  = new Date(temp).format('nn');
    let postMM       = new Date(temp).format('ss');
    let t = postMonth+'月'+postDate+'日 '+postHours+':'+postMinutes+':'+postMM;
    return tip?(postYear+'-'+postMonth+'-'+postDate+' '+postHours+':'+postMinutes+':'+postMM):t
}


let transTime2 = temp => {
    //确保时间戳为13位
    temp = temp.toString().length==10?temp*1000:temp;
    Date.prototype.format = function(format) {
        if (isNaN(this)) return '';
        var o = {
            'm+': this.getMonth() + 1,
            'd+': this.getDate(),
            'h+': this.getHours(),
            'n+': this.getMinutes(),
            's+': this.getSeconds(),
            'S': this.getMilliseconds(),
            'W': ["日", "一", "二", "三", "四", "五", "六"][this.getDay()],
            'q+': Math.floor((this.getMonth() + 3) / 3)
        };
        if (format.indexOf('am/pm') >= 0) {
            format = format.replace('am/pm', (o['h+'] >= 12) ? '下午' : '上午');
            if (o['h+'] >= 12) o['h+'] -= 12;
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }
    let postYear     = new Date(temp).format('yyyy');
    let postMonth    = new Date(temp).format('mm');
    let postDate     = new Date(temp).format('dd');
    let postHours    = new Date(temp).format('hh');
    let postMinutes  = new Date(temp).format('nn');
    let postMM       = new Date(temp).format('ss');
    return postYear+'/'+postMonth+'/'+postDate+' '+postHours+':'+postMinutes
}

// h5调用native方法
function callHandler(actionName, data, callback) {
    // console.log(actionName,data)
    if(typeof window.bridge != 'undefined'){
        window.bridge.callHandler(actionName, data, function responseCallback(responseData) {
            var resObj = responseData;
            if (typeof responseData == 'string') {
                try{
                    let jsonData = JSON.parse(responseData);
                    if (jsonData) {
                        resObj = jsonData;
                    } 
                }catch(e){
                    console.log(e)
                    // Toast(e)
                }
            }
            if(callback){
                callback(resObj);
            }
            console.log('JS received response:', responseData);
        });
    }
}

// 注册native调用h5方法
function registerHandler(actionName, callback) {
    if(inBBJ()){
        window.bridge.registerHandler(actionName, function(data, responseCallback) {
            console.log('JS Echo called with:', data);
            if (callback) {
                if (typeof data == 'string') {
                    try{
                        let jsonData = JSON.parse(data);
                        if (jsonData) {
                            callback(jsonData);
                        }else{
                            callback(data);
                        }
                    }catch(e){
                        console.log(e)
                        // Toast(e)
                        // alert(e)
                    }
                }else{
                    callback(data);
                }
            }
        });
    }
}


//跳转
let navigateTo = (obj,_vue,type) => {
    return new Promise((resolve,reject) => {
        try{
            if(inBBJ()){
                let datas = {
                    url:window.location.origin+'/#/'+to.fullPath,
                    title:'OTC',
                    needLogin:true,
                    popVC:to.query.replace == 1?true:false,     //跳转的时候是否干掉当前页面
                    hiddenNav:true,     //是否全屏
                }
                callHandler('openUrl',datas,resolve)
            }else{
                type === 'push' && _vue.$router.push(obj);
                type === 'replace' && _vue.$router.replace(obj);
            }
        }catch(e){
            reject(e)
        }
    })
}

//返回
let navigateBack = (target,_vue,special) => {
    if(isMYKEY() && !special) return
    if(inBBJ()){
        let datas = {};
        if(typeof target === 'string' && target.indexOf('http') > -1) datas.url = target
        if(typeof target === 'number') datas.index = target
        callHandler('popUrl',datas)
    }else{
        if(typeof target === 'number') _vue.$router.go(target)
    }
}

//将科学计数法转变成正常用户可视格式
function toNonExponential(num) {
    if(typeof num === 'string') num = Number(num);
    var m = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/);
    return num.toFixed(Math.max(0, (m[1] || '').length - m[2]));
}

//代币合约地址
let addressAbi = {
    USDT:'0xdAC17F958D2ee523a2206206994597C13D831ec7',
    DAI:'0x6b175474e89094c44da98b954eedeac495271d0f'
}

//汇率
let exchanges = {
    ETH:1000000000000000000,
    DAI:1000000000000000000,
    USDT:1000000
}

//配置
// let abiArray = [{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"cap","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"burn","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_subtractedValue","type":"uint256"}],"name":"decreaseApproval","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_addedValue","type":"uint256"}],"name":"increaseApproval","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"burner","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[],"name":"Unpause","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}];
let abiArray = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}];


let checkDialog = () => {
    //下单的时候检测是否需要弹窗
    return new Promise((resolve,reject) => {
        let _hours = new Date().getHours();
        if(_hours >= 8){
            resolve('');
            return
        }
        Dialog.confirm({
            title: '',
            message: '<p>北京时间夜间0点到早上8点</p><p>OTC服务将有所延迟</p><p>并影响到账时间，敬请谅解</p>',
            className:'fullDialog sellType-dialog',
            cancelButtonColor:'#1989fa',
            confirmButtonText:'继续交易',
            cancelButtonText:'取消',
            overlayClass:'sellType-mark'
        }).then(() => {
            resolve('')
            console.log('confirm')
        }).catch(() => {
            reject('')
            console.log('cancel')
        })
    })
}

//读取一些基础配置
const siteConfig = token => {
    return new Promise((resolve,reject) => {
        fetch(ajaxUrl()+`/site/config`,{
            token:token || getToken()
        }).then(res => {
            if(res.retCode === 0){
                resolve(res.retData)
            }else{
                reject('')
            }
        }).catch(error => {
            reject('')
            console.log(error)
        })
    })
}


export default {
	ajaxUrl,
	getQueryString,
	client,
	accAdd,
	subtr,
	accMul,
	accDiv,
    getToken,
    fetch,
    fetch2,
    setStorage,
    setStorage2,
    getStorage,
    getStorage2,
    time,
    bridgeData,
    transTime,
    inBBJ,
    callHandler,
    registerHandler,
    navigateBack,
    waitSDKReady,
    getPriceByName,
    isIphoneX,
    isMYKEY,
    debug,
    eosNetwork,
    transTime2,
    abiArray,
    addressAbi,
    exchanges,
    setIntervalGetAccounts,
    getEOSName,
    toNonExponential,
    checkDialog,
    siteConfig,
    setCookie,
    getCookie,
    delCookie,
    getAccountInfo
}